package experiment3.shudu001.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

import experiment3.shudu001.R;
import experiment3.shudu001.models.GameEngine;
import experiment3.shudu001.views.SudokuBoard;

/**
 * Created by HP on 2025/4/26.
 * 该活动负责管理数独游戏的运行，包括界面展示、游戏计时、用户交互等功能
 */

public class GameActivity extends AppCompatActivity {

    private SudokuBoard sudokuBoard;
    private GameEngine gameEngine;
    private Chronometer timer;
    private TextView mistakesTextView;
    private long timeWhenStopped = 0;
    private Button notesButton;
    private TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        sudokuBoard = (SudokuBoard) findViewById(R.id.sudokuBoard);
        timer = (Chronometer) findViewById(R.id.timer);
        mistakesTextView = (TextView) findViewById(R.id.mistakesTextView);

        int difficulty = getIntent().getIntExtra("difficulty", 1);
        boolean loadSaved = getIntent().getBooleanExtra("loadSaved", false);

        gameEngine = new GameEngine(this, difficulty, loadSaved);
        sudokuBoard.setGameEngine(gameEngine);
        notesButton = (Button) findViewById(R.id.notesButton);
        updateMistakes();

        // 设置按钮点击事件
        findViewById(R.id.pauseButton).setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                pauseGame();
            }
        });
        findViewById(R.id.hintButton).setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                gameEngine.giveHint();
            }
        });
        findViewById(R.id.notesButton).setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                gameEngine.toggleNotesMode();
                notesButton.setSelected(gameEngine.isNotesMode());
            }
        });
        findViewById(R.id.clearButton).setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                gameEngine.eraseCell();
            }
        });

        // 数字按钮
        for (int i = 1; i <= 9; i++) {
            final int number = i;  // 创建一个final的局部变量
            int resId = getResources().getIdentifier("numberButton" + i, "id", getPackageName());
            findViewById(resId).setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(android.view.View v) {
                    gameEngine.setSelectedNumber(number);  // 使用final变量
                }
            });
        }

        startTimer();
    }


    private void startTimer() {
        if (gameEngine.isNewGame()) {
            timer.setBase(SystemClock.elapsedRealtime());
        } else {
            timer.setBase(SystemClock.elapsedRealtime() - gameEngine.getElapsedTime());
        }
        timer.start();
    }

    private void pauseGame() {
        timeWhenStopped = SystemClock.elapsedRealtime() - timer.getBase();
        timer.stop();

        Intent intent = new Intent(this, PauseActivity.class);
        intent.putExtra("timeWhenStopped", timeWhenStopped);
        startActivity(intent);
    }

    public void updateMistakes() {
        mistakesTextView.setText("错误: " + gameEngine.getMistakes() + "/5");
    }

    public void onGameCompleted() {
        timer.stop();
        long elapsedTime = SystemClock.elapsedRealtime() - timer.getBase();
        Intent intent = new Intent(this, CompletionActivity.class);
        intent.putExtra("isSuccess", true);  // 新增参数
        intent.putExtra("time", elapsedTime);
        intent.putExtra("difficulty", gameEngine.getDifficulty());
        intent.putExtra("mistakes", gameEngine.getMistakes());
        startActivity(intent);
        finish();
    }

    public void onGameFailed() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timer.stop();
                Intent intent = new Intent(GameActivity.this, CompletionActivity.class);
                intent.putExtra("isSuccess", false);
                intent.putExtra("mistakes", gameEngine.getMistakes());
                startActivity(intent);
                finish();
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timeWhenStopped = SystemClock.elapsedRealtime() - timer.getBase();
            timer.stop();
        }
        gameEngine.saveGame(timeWhenStopped);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timer != null && !gameEngine.isGameCompleted()) {
            timer.setBase(SystemClock.elapsedRealtime() - timeWhenStopped);
            timer.start();
        }
    }
    public void showErrorToast() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(GameActivity.this, "输入有冲突！错误次数：" + gameEngine.getMistakes(), Toast.LENGTH_SHORT).show();
                updateMistakes();
            }
        });
    }
}